package com.css.zfzx.fwsjcj.modules.taskmanage.task.repository.Impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.org.user.repository.UserRepository;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.fwsjcj.commen.util.Constant;
import com.css.zfzx.fwsjcj.commen.util.ServerUtil;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupEntity;
import com.css.zfzx.fwsjcj.modules.group.entity.FwGroupUserEntity;
import com.css.zfzx.fwsjcj.modules.group.service.FwGroupService;
import com.css.zfzx.fwsjcj.modules.group.service.FwGroupUserService;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.entity.FwTaskEntity;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.repository.TaskQueryRepsitory;
import com.css.zfzx.fwsjcj.modules.taskmanage.task.vo.TaskQueryVo;
import com.css.zfzx.fwsjcj.modules.user.entity.FwUserEntity;
import com.css.zfzx.fwsjcj.modules.user.service.FwUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@PropertySource("classpath:platform-config.yml")
@Repository
public class TaskQueryRepsitoryImpl implements TaskQueryRepsitory {
    @PersistenceContext
    EntityManager entityManager;
    @Autowired
    FwGroupUserService fwGroupUserService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    FwGroupService fwGroupService;
    @Autowired
    private DivisionRepository divisionRepository;
    // 超级管理员、省、市管理员编号
    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.taskCode}")
    private String taskCode;
    @Value("${role.xcCollectCode}")
    private String xcCollectCode;
    @Autowired
    FwUserService fwUserService;
    @Override
    public Page<FwTaskEntity> getPage(String type, HttpServletRequest request, TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select distinct * from fw_task");
        // 条件查询sql
        StringBuilder whereSql = new StringBuilder(" where del_flag = '" + Constant.IS_VALID_YES + "'");
        if (!StringUtils.isEmpty(taskQueryVo.getStatus())) {
            whereSql.append(" and status =:status");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            whereSql.append(" and task_name like :taskName");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            whereSql.append(" and group_leader like :groupLeader");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getDivision())) {
            whereSql.append(" and division like :division");
        }
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为任务管理员
        boolean containtRoleTask=ServerUtil.isContaintRole(roles,taskCode);
        if (!containtRole) {
            if (containtRolePro || containtRoleCity) {
                whereSql.append(" and division like :divisionName");
            }
        }
        whereSql.append(" and task_type = " + type);
        // 排序
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        /**
         * 1.条件查询实体list
         */
        Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwTaskEntity.class);

        StringBuilder coutsql = new StringBuilder(" select count(*) from fw_task");
        /**
         * 2.条件查询数量
         */
        Query countQuery = entityManager.createNativeQuery(coutsql.append(whereSql).toString());

        /**
         * 查询参数设值
         */
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            nativeQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
            countQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            nativeQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
            countQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getStatus())) {
            nativeQuery.setParameter("status", taskQueryVo.getStatus());
            countQuery.setParameter("status", taskQueryVo.getStatus());
        }

        if (!StringUtils.isEmpty(taskQueryVo.getDivision())) {
            nativeQuery.setParameter("division", "%" + taskQueryVo.getDivision() + "%");
            countQuery.setParameter("division", "%" + taskQueryVo.getDivision() + "%");
        }
        if (!containtRole) {
            if (containtRolePro || containtRoleCity) {
                DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
                String divisionId = mainDept.getDivisionId();
                DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
                String divisionName = validDivisionById.getDivisionName();
                nativeQuery.setParameter("divisionName", "%" + divisionName + "%");
                countQuery.setParameter("divisionName", "%" + divisionName + "%");
            }
        }
        // 设置分页信息
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        // 具体一页的实体list和总条数
        List<FwTaskEntity> firstResult = nativeQuery.getResultList();
        BigInteger bigInteger = (BigInteger) countQuery.getSingleResult();
        // 数据封装成page返回
        Page<FwTaskEntity> page = new PageImpl<>(firstResult, pageable, bigInteger.longValue());
        return page;
    }

    @Override
    public Page<FwTaskEntity> findPage(String type, int curtPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select * from fw_task");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '" + Constant.IS_VALID_YES + "'");
        String userId = PlatformSessionUtils.getUserId();
        List<FwGroupUserEntity> byUserId = fwGroupUserService.findByUserId(userId);
        List<FwGroupEntity> byGroupLeaderId = fwGroupService.findByGroupLeaderId(userId);
        if (byUserId.size() <= 0 && byGroupLeaderId.size() <= 0) {
            List<FwTaskEntity> arrList = new ArrayList<>();
            Pageable pageable = PageRequest.of(curtPage - 1, pageSize);
            Page<FwTaskEntity> page = new PageImpl<>(arrList, pageable, 0L);
            return page;
        }
        List<String> ids = new ArrayList<>();
        if (!StringUtils.isEmpty(byUserId) && byUserId.size() > 0) {
            for (FwGroupUserEntity entity : byUserId) {
                ids.add(entity.getGroupId());
            }
        }
        if (!StringUtils.isEmpty(byGroupLeaderId) && byGroupLeaderId.size() > 0) {
            byGroupLeaderId.forEach(fwGroupEntity -> {
                ids.add(fwGroupEntity.getId());
            });
        }
        if (!StringUtils.isEmpty(type)) {
            whereSql.append(" and status = :type");
        }
        if (!StringUtils.isEmpty(ids) && ids.size() > 0) {
            if (!StringUtils.isEmpty(userId)) {
                whereSql.append(" and group_id in :ids");
            }
        }
        FwUserEntity fwUserEntity = fwUserService.findByBaseUserId(userId);
        if(!StringUtils.isEmpty(fwUserEntity)) {
            if(Constant.USER_TYPE_PC.equals(fwUserEntity.getUserType())) {
                whereSql.append(" and task_type = :taskType");
            }
            if(Constant.USER_TYPE_JG.equals(fwUserEntity.getUserType())){
                whereSql.append(" and task_type = :taskType");
            }
            if(Constant.USER_TYPE_JG_ANG_PC.equals(fwUserEntity.getUserType())){
                whereSql.append(" and task_type in :taskType");
            }
        }
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwTaskEntity.class);
        StringBuilder coutsql = new StringBuilder(" select count(*) from fw_task");
        Query countQuery = entityManager.createNativeQuery(coutsql.append(whereSql).toString());
        if (!StringUtils.isEmpty(type)) {
            nativeQuery.setParameter("type", type);
            countQuery.setParameter("type", type);
        }
        if (!StringUtils.isEmpty(ids) && ids.size() > 0) {
            if (!StringUtils.isEmpty(ids)) {
                nativeQuery.setParameter("ids", ids);
                countQuery.setParameter("ids", ids);
            }
        }
        if(!StringUtils.isEmpty(fwUserEntity)) {
            if(Constant.USER_TYPE_PC.equals(fwUserEntity.getUserType())) {
                nativeQuery.setParameter("taskType",Constant.TASK_TYPE_PU);
                countQuery.setParameter("taskType",Constant.TASK_TYPE_PU);
            }
            if(Constant.USER_TYPE_JG.equals(fwUserEntity.getUserType())){
                nativeQuery.setParameter("taskType",Constant.TASK_TYPE_JG);
                countQuery.setParameter("taskType",Constant.TASK_TYPE_JG);
            }
            if(Constant.USER_TYPE_JG_ANG_PC.equals(fwUserEntity.getUserType())){
                List<String> list=new ArrayList<>();
                list.add(Constant.TASK_TYPE_PU);
                list.add(Constant.TASK_TYPE_JG);
                nativeQuery.setParameter("taskType",list);
                countQuery.setParameter("taskType",list);
            }
        }
        Pageable pageable = PageRequest.of(curtPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        List<FwTaskEntity> resultList = nativeQuery.getResultList();
        BigInteger countNum = (BigInteger) countQuery.getSingleResult();

        Page<FwTaskEntity> page = new PageImpl<>(resultList, pageable, countNum.longValue());
        return page;
    }

    @Override
    public Page<FwTaskEntity> getPage(TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select distinct * from fw_task");
        // 条件查询sql
        StringBuilder whereSql = new StringBuilder(" where del_flag = '" + Constant.IS_VALID_YES + "'");
        // 任务名称和组长
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            whereSql.append(" and task_name like :taskName");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            whereSql.append(" and group_leader like :groupLeader");
        }
        // 质检状态
        if (!StringUtils.isEmpty(taskQueryVo.getQualityStatus())) {
            whereSql.append(" and quality_status = " + taskQueryVo.getQualityStatus());
        } else {
            whereSql.append(" and quality_status != 0");
        }
        // 普查任务类型为0
        whereSql.append(" and task_type = 0");
        // 排序
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");

        /**
         * 1.条件查询实体list
         */
        Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwTaskEntity.class);

        /**
         * 2.条件查询数量
         */
        StringBuilder coutsql = new StringBuilder(" select count(*) from fw_task");
        Query countQuery = entityManager.createNativeQuery(coutsql.append(whereSql).toString());
        /**
         * 查询参数设值
         */
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            nativeQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
            countQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            nativeQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
            countQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
        }
        // 设置分页信息
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        // 具体一页的实体list和总条数
        List<FwTaskEntity> firstResult = nativeQuery.getResultList();
        BigInteger bigInteger = (BigInteger) countQuery.getSingleResult();
        // 数据封装成page返回
        Page<FwTaskEntity> page = new PageImpl<>(firstResult, pageable, bigInteger.longValue());
        return page;
    }

    @Override
    public Page<FwTaskEntity> getPageByUser(TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select distinct * from fw_task");
        // 条件查询sql
        StringBuilder whereSql = new StringBuilder(" where del_flag = '" + Constant.IS_VALID_YES + "'");

        // 查询当前用户
        String userId = PlatformSessionUtils.getUserId();
        // 获取当前登录用户角色
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 角色列表里面是否包含超级管理员
        boolean containtSuperRole = ServerUtil.isContaintRole(roles, superCode);
        // 超级管理员可以看到所有
        if (!containtSuperRole) {
            whereSql.append(" and quality_id like :userId");
        }

        // 任务名称和组长
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            whereSql.append(" and task_name like :taskName");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            whereSql.append(" and group_leader like :groupLeader");
        }
        // 质检状态
        if (!StringUtils.isEmpty(taskQueryVo.getQualityStatus())) {
            whereSql.append(" and quality_status = " + taskQueryVo.getQualityStatus());
        } else {
            whereSql.append(" and quality_status != 0");
        }
        // 普查任务类型为0
        whereSql.append(" and task_type = 0");

        // 排序
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        /**
         * 1.条件查询实体list
         */
        Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwTaskEntity.class);

        /**
         * 2.条件查询数量
         */
        StringBuilder coutsql = new StringBuilder(" select count(*) from fw_task");
        Query countQuery = entityManager.createNativeQuery(coutsql.append(whereSql).toString());
        /**
         * 模糊查询参数设值
         */
        if (!StringUtils.isEmpty(userId) && !containtSuperRole) {
            nativeQuery.setParameter("userId", "%" + userId + "%");
            countQuery.setParameter("userId", "%" + userId + "%");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            nativeQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
            countQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            nativeQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
            countQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
        }
        // 设置分页信息
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        // 具体一页的实体list和总条数
        List<FwTaskEntity> firstResult = nativeQuery.getResultList();
        BigInteger bigInteger = (BigInteger) countQuery.getSingleResult();
        // 数据封装成page返回
        Page<FwTaskEntity> page = new PageImpl<>(firstResult, pageable, bigInteger.longValue());
        return page;
    }

    @Override
    public Page<FwTaskEntity> getPageTask(String type, HttpServletRequest request, TaskQueryVo taskQueryVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder(" select distinct * from fw_task");
        // 条件查询sql
        StringBuilder whereSql = new StringBuilder(" where del_flag = '" + Constant.IS_VALID_YES + "'");
        if (!StringUtils.isEmpty(taskQueryVo.getStatus())) {
            whereSql.append(" and status =:status");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            whereSql.append(" and task_name like :taskName");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            whereSql.append(" and group_leader like :groupLeader");
        }

        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //查看用户所属的小组
        List<FwGroupEntity> byGroupLeaderId = fwGroupService.findByGroupLeaderId(userId);
        List<String> listGroupId = new ArrayList<>();
        if(byGroupLeaderId.size()>0){
            byGroupLeaderId.forEach(fwGroupEntity -> {
                listGroupId.add(fwGroupEntity.getId());
            });
        }
        List<FwGroupUserEntity> byUserId = fwGroupUserService.findByUserId(userId);
        if(byUserId.size()>0) {
            byUserId.forEach(fwGroupUserEntity -> {
                listGroupId.add(fwGroupUserEntity.getGroupId());
            });
        }
        List<String> collect = listGroupId.stream().distinct().collect(Collectors.toList());
        if(collect.size()>0) {
            whereSql.append(" and group_id in :groupId ");
        }else {
                List<FwTaskEntity> arrList = new ArrayList<>();
                Pageable pageable = PageRequest.of(curPage - 1, pageSize);
                Page<FwTaskEntity> page = new PageImpl<>(arrList, pageable, 0L);
                return page;
        }
        whereSql.append(" and task_type = " + type);
        // 排序
        StringBuilder orderBy = new StringBuilder(" order by create_time desc");
        /**
         * 1.条件查询实体list
         */
        Query nativeQuery = entityManager.createNativeQuery(sql.append(whereSql).append(orderBy).toString(), FwTaskEntity.class);

        StringBuilder coutsql = new StringBuilder(" select count(*) from fw_task");
        /**
         * 2.条件查询数量
         */
        Query countQuery = entityManager.createNativeQuery(coutsql.append(whereSql).toString());

        /**
         * 查询参数设值
         */
        if (!StringUtils.isEmpty(taskQueryVo.getTaskName())) {
            nativeQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
            countQuery.setParameter("taskName", "%" + taskQueryVo.getTaskName() + "%");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getGroupLeader())) {
            nativeQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
            countQuery.setParameter("groupLeader", "%" + taskQueryVo.getGroupLeader() + "%");
        }
        if (!StringUtils.isEmpty(taskQueryVo.getStatus())) {
            nativeQuery.setParameter("status", taskQueryVo.getStatus());
            countQuery.setParameter("status", taskQueryVo.getStatus());
        }
        if(collect.size()>0) {
            nativeQuery.setParameter("groupId", collect);
            countQuery.setParameter("groupId", collect);
        }
        // 设置分页信息
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        nativeQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        nativeQuery.setMaxResults(pageable.getPageSize());
        // 具体一页的实体list和总条数
        List<FwTaskEntity> firstResult = nativeQuery.getResultList();
        BigInteger bigInteger = (BigInteger) countQuery.getSingleResult();
        // 数据封装成page返回
        Page<FwTaskEntity> page = new PageImpl<>(firstResult, pageable, bigInteger.longValue());
        return page;
    }

}
